package com.frontop.bigdata.modules.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.frontop.bigdata.modules.model.BigDataAccessPage;
import com.frontop.bigdata.modules.mapper.BigDataAccessPageMapper;
import com.frontop.bigdata.modules.model.BigDataAccessPageInfo;
import com.frontop.bigdata.modules.service.BigDataAccessPageInfoService;
import com.frontop.bigdata.modules.service.BigDataAccessPageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.frontop.bigdata.util.BaiduDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 大数据统计--受访页面统计 服务实现类
 * </p>
 *
 * @author YangJia
 * @since 2022-02-11
 */
@Service
public class BigDataAccessPageServiceImpl extends ServiceImpl<BigDataAccessPageMapper, BigDataAccessPage> implements BigDataAccessPageService {
    @Autowired
    BigDataAccessPageInfoService bigDataAccessPageInfoService;
    @Autowired
    BigDataAccessPageMapper bigDataAccessPageMapper;

    @Override
    @Transactional
    public void pullAccessPageData(Long siteId, String date) {
        JSONObject body = new JSONObject();
        body.put("site_id",siteId);
        body.put("start_date",date);
        body.put("end_date",date);
        //浏览量，访客数，IP 数，入口页次数，退出页次数，平均停留时长（秒），退出率（%）
        body.put("metrics","pv_count,visitor_count,ip_count,visit1_count,exit_count,average_stay_time,exit_ratio");
        body.put("method","visit/toppage/a");

        JSONObject result = BaiduDataUtil.requestBaidu(body);

        if(result != null){
            if(result.getJSONObject("body").getJSONArray("data").size() == 0){
                return;
            }
            //获取页面列表
            JSONArray pageList = result
                    .getJSONObject("body")
                    .getJSONArray("data")
                    .getJSONObject(0)
                    .getJSONObject("result")
                    .getJSONArray("items").getJSONArray(0);

            //获取数据列表
            JSONArray valueList = result
                    .getJSONObject("body")
                    .getJSONArray("data")
                    .getJSONObject(0)
                    .getJSONObject("result")
                    .getJSONArray("items").getJSONArray(1);

            if(pageList != null && pageList.size()>0){
                List<BigDataAccessPage> bigDataAccessPageList = new ArrayList<>();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
                for(int i=0;i<pageList.size();i++){
                    BigDataAccessPage bigDataAccessPage = new BigDataAccessPage();
                    //页面信息
                    JSONObject page = pageList.getJSONArray(i).getJSONObject(0);
                    //统计数据
                    JSONArray value = valueList.getJSONArray(i);
                    bigDataAccessPage.setPvCount(value.getInteger(0));
                    bigDataAccessPage.setVisitorCount(value.getInteger(1));
                    bigDataAccessPage.setIpCount(value.getInteger(2));
                    bigDataAccessPage.setVisit1Count(value.getInteger(3));
                    bigDataAccessPage.setExitCount(value.getInteger(4));
                    bigDataAccessPage.setAverageStayTime(value.getInteger(5));
                    bigDataAccessPage.setExitRatio(value.getBigDecimal(6));
                    bigDataAccessPage.setPageId(page.getString("pageId"));
                    //检查页面信息列表数据中存不存在 如果不存在就添加新的页面信息数据 并且 地址中需包含frontopbd字符（避免出现本地路径）
                    if(bigDataAccessPageInfoService.getById(page.getString("pageId")) == null && page.getString("name").contains("frontopbd")){
                        BigDataAccessPageInfo bginfo = new BigDataAccessPageInfo();
                        bginfo.setPageId(page.getString("pageId"));
                        bginfo.setStatus(0);
                        bginfo.setPagePath(page.getString("name"));
                        bginfo.setPageName(page.getString("name"));
                        bginfo.setSiteId(siteId);
                        bginfo.setCreateTime(new Date());
                        bigDataAccessPageInfoService.save(bginfo);
                    }
                    Map<String,Object> map = new HashMap<>();
                    try {
                        bigDataAccessPage.setStatisticsDate(formatter.parse(date));
                        map.put("statistics_date",formatter.parse(date));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    bigDataAccessPage.setCreateTime(new Date());
                    map.put("page_id",page.getString("pageId"));
                    //删除页面站点当天的数据 ，避免重复
                    removeByMap(map);
                    bigDataAccessPageList.add(bigDataAccessPage);
                }
                //入库
                saveBatch(bigDataAccessPageList);
            }

        }
    }

    @Override
    public List<JSONObject>  getPageVariousTotal(Integer orgId) {
        return bigDataAccessPageMapper.getPageVariousTotal(orgId);
    }

    @Override
    public List<JSONObject> getPageVariousTotalBySevenDays(Integer orgId) {
        return bigDataAccessPageMapper.getPageVariousTotalBySevenDays(orgId);
    }


}